package util.completable_future;

import exception.UnifiedExceptionConsole;
import gnu.io.SerialPort;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import model.SerialPortUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.Common;
import util.LoadConfigInfo;

import java.io.*;
import java.util.function.Supplier;

public class SendFileSupplier implements Supplier<Integer> {

    private final static Logger logger = LoggerFactory.getLogger(SendFileSupplier.class);

    private final File file;
    private final SerialPort serialPort;
    private Integer sendLength;
    private final Label sendDataLength;

    private final LoadConfigInfo loadConfigInfo = new LoadConfigInfo();

    public SendFileSupplier(File file, SerialPort serialPort, Integer sendLength, Label sendDataLength) {
        this.file = file;
        this.serialPort = serialPort;
        this.sendLength = sendLength;
        this.sendDataLength = sendDataLength;
    }

    @Override
    public Integer get() {

        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream(file), loadConfigInfo.getSerialPortSendDataCharsetName());
        } catch (Exception e) {
            UnifiedExceptionConsole.console(e);
        }
        if (reader == null) {
            Common.alert(Alert.AlertType.WARNING, "警告", "打开的文件为空文件！");
            return null;
        }
        //读取
        BufferedReader bfreader = new BufferedReader(reader);
        //按行读取文件数据
        String line;
        try {
            while ((line = bfreader.readLine()) != null) {
                line = line + "\n";
                //注意：此处获取字符串的二进制编码格式与文件编码格式一致
                byte[] bytes = line.getBytes(loadConfigInfo.getSerialPortSendDataCharsetName());
                //按行发送数据，以文件编码格式发送数据
                SerialPortUtil.sendData(serialPort, bytes, loadConfigInfo.getSerialPortSendDataCharsetName());
                //更新实际发送的数据长度
                sendLength = sendLength + bytes.length;
                Platform.runLater(() -> {
                    //显示更新后的数据长度
                    sendDataLength.setText("Send: " + sendLength);
                });

            }
        } catch (IOException ex) {
            logger.error("IOException", ex);
        }
        try {
            reader.close();
            bfreader.close();
        } catch (IOException ex) {
            logger.error("IOExceptionn", ex);
        }
        return sendLength;
    }
}
